<template>
  <el-dialog
    v-model="visible"
    width="1000px"
    title="转换器测试"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    @closed="dialogClosed"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <div>function transform(data) {</div>
        <CodeEditor v-model:value="form.script" height="500px" />
        <div>}</div>
      </el-col>
      <el-col :span="12">
        <div>输入</div>
        <CodeEditor v-model:value="testInput" height="240px" />
        <div>输出</div>
        <CodeEditor v-model:value="testOutput" height="240px" />
      </el-col>
    </el-row>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSave">保 存</el-button>
        <el-button type="primary" :loading="testLoading" @click="handleTest">执 行</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
  import { ref, watch, computed, defineProps, defineEmits } from 'vue';
  import { onlineTest } from '@/api/web/db/transformer';
  import { CodeEditor } from '@/components/CodeEditor';
  import beautifier from 'js-beautify';
  import modal from '@/plugins/modal';

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    currentItem: {
      type: Object,
      default: () => ({}),
    },
  });

  const emits = defineEmits(['update:modelValue', 'save']);

  const visible = computed({
    set(val) {
      emits('update:modelValue', val);
    },
    get() {
      return props.modelValue;
    },
  });

  const form = ref({});
  const testLoading = ref(false);
  const testInput = ref('');
  const testOutput = ref('');

  watch(visible, (v) => {
    if (v) {
      form.value = { ...props.currentItem };
    }
  });

  function handleSave() {
    emits('save', form.value);
    visible.value = false;
  }

  function handleTest() {
    if (!form.value.script || !testInput.value) {
      modal.msgError('脚本和输入不能为空');
      return;
    }

    const params = {
      script: form.value.script,
      param: testInput.value,
    };
    testLoading.value = true;
    onlineTest(params)
      .then((res) => {
        testOutput.value = beautifier(JSON.stringify(res.data) || '', {
          indent_size: 2,
          space_in_empty_paren: true,
        });
      })
      .finally(() => {
        testLoading.value = false;
      });
  }

  function dialogClosed() {
    form.value = {};
    testLoading.value = false;
    testInput.value = '';
    testOutput.value = '';
  }
</script>
